package com.song.client;

import com.song.transport.RPCResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理 所有的未处理的RPCRequest
 * 存放了未处理的请求（建议限制 map 容器大小，避免未处理请求过多 OOM
 */
@Slf4j(topic = "c.UnprocessedRequests")
public class UnprocessedRequests {

    private static ConcurrentHashMap<String, CompletableFuture<RPCResponse>> unprocessResponseFuture = new ConcurrentHashMap<>();

    public void put(String requestId, CompletableFuture<RPCResponse> future) {
        unprocessResponseFuture.put(requestId, future);
    }

    public void remove(String requestId) {
        unprocessResponseFuture.remove(requestId);
    }

    public void complete(RPCResponse response) {
        CompletableFuture<RPCResponse> future = unprocessResponseFuture.remove(response.getResquestId());
        if(null != future) {
                future.complete(response);//返回CompletableFuture的异步计算结果，传给RPCClientProxy类的sendRequest发送rpcRequest时的CompletableFuture  get()获取
            } else {
                log.info("未收到服务端返回的RPCResponse数据：");
                throw new RuntimeException();
            }
    }
}
